<template>
  <div class="login_container">
    <div class="headBox">
      <img src="@/assets/images/cmmop_logo.png" alt />
      <div class="logoText">
        <span>磐石致维</span>
        <span>Combined Maintenance and Management Operation Platform for Police Information Systems</span>
      </div>
    </div>
    <div class="main">
      <div class="main_bg"></div>
      <div class="login_main">
        <!-- 找回密码 -->
        <el-form ref="loginFormRef2" class="loginFormRef2" v-show="!isWanjimima" :model="loginForm2" :rules="rulesForm2" label-width="0px">
          <el-form-item>
            <div class="switchBtn2 headerBtn">
              <span>找回密码</span>
            </div>
          </el-form-item>
          <el-form-item prop="username2">
            <el-input placeholder="请输入手机号码" autocomplete="off" v-model.trim="loginForm2.username2" maxlength="11"></el-input>
          </el-form-item>
          <el-form-item prop="duanxin">
            <el-input placeholder="输入短信验证码" autocomplete="off" v-model.trim="loginForm2.duanxin" maxlength="6">
              <el-button type="text" slot="suffix" class="huoquyanma" :disabled="canClick2" @click="getyanma2" v-preventReClick>{{ contents2 }}</el-button>
            </el-input>
          </el-form-item>
          <el-form-item prop="password2">
            <el-input autocomplete="off" onfocus="this.type='password'" type="text" placeholder="设置密码（6-15个字)" v-model.trim="loginForm2.password2" maxlength="15"></el-input>
          </el-form-item>
          <el-form-item class="btns">
            <el-button type="primary" @click="xiugaimima" v-preventReClick>确认修改</el-button>
          </el-form-item>
          <el-form-item class="btns2">
            <span style="color: #fff; opacity: 0.6">已有账号？</span>
            <el-button type="text" @click="wanjimima">登录</el-button>
          </el-form-item>
        </el-form>
        <!-- 登入输入框 -->
        <el-form ref="loginFormRef" v-show="isWanjimima" :model="loginForm" :rules="rulesForm" label-width="0px" class="formBox" :validate-on-rule-change="false">
          <el-form-item>
            <div class="switchBtn headerBtn">
              <span :class="isOkBTN" @click="mima">密码登录</span>
              <span :class="isOkBTN2" @click="yanzhengma">验证码登录</span>
            </div>
          </el-form-item>
          <el-form-item prop="username">
            <el-input autocomplete="off" :placeholder="yonhuText" @keyup.enter.native="login()" v-model.trim="loginForm.username">
              <svg class="iconfont" slot="prefix" aria-hidden="true" style="width: 14px; height: 16px; vertical-align: middle">
                <use :xlink:href="'#el-icon-my' + svgBox.vals1" style="font-size: 50px" />
              </svg>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input autocomplete="off" :placeholder="mimaText" @keyup.enter.native="login()" v-model.trim="loginForm.password" :type="isPassword">
              <svg class="iconfont" slot="prefix" aria-hidden="true" style="width: 14px; height: 16px; vertical-align: middle">
                <use :xlink:href="'#el-icon-my' + svgBox.vals2" style="font-size: 50px" />
              </svg>
              <el-button v-show="duanxing" type="text" slot="suffix" class="huoquyanma" :disabled="canClick" @click="getyanma" v-preventReClick>{{ contents }}</el-button>
            </el-input>
          </el-form-item>
          <el-form-item class="btns">
            <el-button type="primary" @click="login()" v-preventReClick :loading="loginLoad">
              <span style="fontsize: 16px">立即登录</span>
            </el-button>
          </el-form-item>
          <el-form-item class="btns2">
            <el-button type="text" class="text2Box" @click="downloadApp">下载守望者APP</el-button>
            <el-button type="text" @click="wanjimima">忘记密码</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-link href="https://www.hntohere.com" class="footer" :underline="false" target="_blank">© 2020-{{ year }} 湖南同恒信息技术有限公司 版权所有</el-link>

    <el-dialog title="下载守望者APP" :visible.sync="showApp" :modal="true" :append-to-body="true" width="15%">
      <!-- logoSrc为logo的url地址(使用require的方式)；text为需要转换为二维码的内容  :logoSrc="imageUrl"-->
      <!-- https://cmmop.hnlot.com.cn/android/cmmop.apk -->
      <div class="qrBox">
        <vue-qr text="https://cmmop.hnlot.com.cn/android/apk/cmmop.apk" :size="200"></vue-qr>
        <span class="textsApp">仅支持安卓手机用户</span>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// import { setUrl } from '../utils/getUrl.js'
import { pinT } from '../utils/allUrl.js'
import { timestampToTime } from '@/assets/js/setTime'

import { getUrl, setUrl, removeUrl } from '@/utils/getUrl.js'
// 二维码生成器
import vueQr from 'vue-qr'
export default {
  data: function () {
    return {
      // 登入
      loginForm: {
        username: '',
        password: '',
      },
      // 找回密码
      loginForm2: {
        username2: '',
        password2: '',
        duanxin: '',
      },
      zhanhaoNum: 16, // 账号长度
      mimaNum: 15, // 密码长度
      isWanjimima: true,
      isPassword: 'password',
      yonhuText: '登录账号/手机号码/邮箱',
      mimaText: '请输入登录密码',
      duanxing: false, // 获取验证吗
      isOkBTN: 'isShowBtn',
      isOkBTN2: '',
      contents: '获取验证码',
      totalTime: 60,
      canClick: false,
      contents2: '获取验证码',
      totalTime2: 60,
      canClick2: false,
      svgBox: {
        vals1: 'account_number',
        vals2: 'Login_password',
      },
      //   这时表单的验证规则对象
      rulesForm: {
        //   验证用户名
        username: [
          { required: true, message: '请输入登录账号/手机号码', trigger: 'blur' },
          // { min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur' }
        ],
        // 验证密码
        password: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          // { min: 6, max: 15, message: '请输入6~15位数密码', trigger: 'blur' }
        ],
      },
      rulesForm2: {
        //   验证用户名
        username2: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1(3|4|5|6|7|8|9)\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
        ],
        // 验证密码
        password2: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          { min: 6, max: 15, message: '请输入6~15位数密码', trigger: 'blur' },
        ],
        // 短信验证
        duanxin: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { max: 6, message: '请输入6位数验证码', trigger: 'blur' },
        ],
      },
      loginLoad: false,
      showApp: false, // app
      year: '',
    }
  },
  created() {
    this.year = timestampToTime().year
  },
  // 二维码生成器
  components: {
    vueQr,
  },
  methods: {
    // 密码登录
    async mima() {
      this.$refs.loginFormRef.resetFields()
      this.isOkBTN = 'isShowBtn'
      this.isOkBTN2 = ''
      this.yonhuText = '登录账号/手机号码/邮箱'
      this.mimaText = '请输入登录密码'
      this.duanxing = false
      this.isPassword = 'password'
      this.zhanhaoNum = 16
      this.mimaNum = 15
      this.loginLoad = false
      this.svgBox = {
        vals1: 'account_number',
        vals2: 'Login_password',
      }
      this.rulesForm = {
        // 验证用户名
        username: [
          { required: true, message: '登录账号/手机号码', trigger: 'blur' },
          // { min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur' }
        ],
        // 验证密码
        password: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          // { min: 6, max: 15, message: '请输入6~15位数密码', trigger: 'blur' }
        ],
      }
    },
    // 手机验证码登录
    async yanzhengma() {
      this.$refs.loginFormRef.resetFields()
      this.isOkBTN = ''
      this.isOkBTN2 = 'isShowBtn'
      this.yonhuText = '请输入手机号码'
      this.mimaText = '请输入短信验证码'
      this.duanxing = true
      this.isPassword = 'text'
      this.zhanhaoNum = 11
      this.mimaNum = 6
      this.loginLoad = false
      this.svgBox = {
        vals1: 'phone_number',
        vals2: 'Verification_Code',
      }
      this.rulesForm = {
        // 验证用户名
        username: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1(3|4|5|6|7|8|9)\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
        ],
        // 验证密码
        password: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { max: 6, message: '请输入6位数验证码', trigger: 'blur' },
        ],
      }
    },
    // 验证码倒计时
    getyanma() {
      const { username } = this.loginForm
      this.$refs.loginFormRef.validateField('username', async (valid) => {
        if (!valid) {
          this.canClick = true
          var clock = window.setInterval(() => {
            this.totalTime--
            this.contents = this.totalTime + ' S 后重试'
            if (this.totalTime < 1) {
              // 当倒计时小于0时清除定时器
              window.clearInterval(clock)
              this.contents = '获取验证码'
              this.totalTime = 60
              this.canClick = false
            }
          }, 1000)
          const params = new URLSearchParams()
          params.append('userMobile', username)
          params.append('sendByLogin', 'abc')
          params.append('type', false)
          const { data: res } = await this.$http.post(`${pinT}yonghu/userSendSmsCode`, params)
          if (res.code === '0014') {
            return ''
          } else if (res.code !== '0000') {
            window.clearInterval(clock)
            this.contents = '获取验证码'
            this.totalTime = 60
            this.canClick = false
            return this.$message({
              type: 'error',
              message: res.message,
              center: true,
            })
          }
        }
      })
    },
    // 验证码倒计时
    getyanma2() {
      const { username2 } = this.loginForm2
      this.$refs.loginFormRef2.validateField('username2', async (valid) => {
        if (!valid) {
          this.canClick2 = true
          var clock2 = window.setInterval(() => {
            this.totalTime2--
            this.contents2 = this.totalTime2 + ' S 后重试'
            if (this.totalTime2 < 1) {
              // 当倒计时小于0时清除定时器
              window.clearInterval(clock2)
              this.contents2 = '获取验证码'
              this.totalTime2 = 60
              this.canClick2 = false
            }
          }, 1000)
          const params = new URLSearchParams()
          params.append('userMobile', username2)
          params.append('sendByLogin', 'abc')
          params.append('type', false)
          const { data: res } = await this.$http.post(`${pinT}yonghu/userSendSmsCode`, params)
          if (res.code === '0014') {
            return ''
          } else if (res.code !== '0000') {
            window.clearInterval(clock2)
            this.contents2 = '获取验证码'
            this.totalTime2 = 60
            this.canClick2 = false
            return this.$message({
              type: 'error',
              message: res.message,
              center: true,
            })
          }
        }
      })
    },
    // 提交按钮
    login() {
      // 清除上一次界面保存状态
      removeUrl('tabs')
      removeUrl('tabsnum')
      // 离开界面清除最后一次打开状态
      sessionStorage.setItem('activeMenuKey', '')
      setUrl('suaxinTag', '') // 刷新后位置/
      getUrl('tabsnum', '') // 刷新后位置背景色
      setUrl('tabs', '')
      const { username, password } = this.loginForm
      this.$refs.loginFormRef.validate(async (valid) => {
        if (!valid) return true
        this.loginLoad = true
        const lajis = setTimeout(() => {
          if (this.loginLoad) {
            this.loginLoad = false
          }
        }, 5000)
        if (this.duanxing) {
          const params2 = new URLSearchParams()
          params2.append('LXDH', username)
          params2.append('SMSCODE', password)
          const { data: res } = await this.$http.post(`${pinT}yonghu/loginByMobile`, params2)
          clearTimeout(lajis)
          this.loginLoad = false
          if (res.code !== '0000') {
            this.loginLoad = false
            return this.$message({
              type: 'error',
              message: res.message,
              center: true,
            })
          }
          setUrl('userconter', JSON.stringify(res.data.user))
          setUrl('menus', JSON.stringify(res.data.menus))
          // this.$message.success('登录成功')
          // 将登入成功后的token，保存到客户端的sessionStorage中
          // A:项目中除了登入之外的其他API接口，必须登入之后才能访问
          // B:token只有在网站打开期间生效，所以要将token保存到客户端的sessionStorage中
          setUrl('X-Cmmop-User-Token', res.data.access_token)
          localStorage.setItem('userName', res.data.user.zh)
          // 通过编程式导航跳转到后台
          this.$router.push('/home')
        } else {
          const params = new URLSearchParams()
          params.append('ZH', username)
          params.append('MM', password)
          const { data: res } = await this.$http.post(`${pinT}yonghu/login`, params)
          clearTimeout(lajis)
          this.loginLoad = false
          switch (res.code) {
            case '0000':
              break
            case '0017':
              return this.$message({
                type: 'error',
                showClose: true,
                message: '账号没有设置角色，无法登录，请联系管理员！',
                duration: 5000,
                center: true,
              })
            default:
              return this.$message({
                type: 'error',
                message: res.message,
                center: true,
              })
          }
          setUrl('userconter', JSON.stringify(res.data.user))
          setUrl('menus', JSON.stringify(res.data.menus))
          // this.$message.success('登录成功')
          // 将登入成功后的token，保存到客户端的sessionStorage中
          // A:项目中除了登入之外的其他API接口，必须登入之后才能访问
          // B:token只有在网站打开期间生效，所以要将token保存到客户端的sessionStorage中
          setUrl('X-Cmmop-User-Token', res.data.access_token)
          localStorage.setItem('userName', res.data.user.zh)
          // 通过编程式导航跳转到后台
          this.$router.push('/home')
        }
      })
    },
    // 修改密码
    xiugaimima() {
      const { username2, password2, duanxin } = this.loginForm2
      this.$refs.loginFormRef2.validate(async (valid) => {
        if (!valid) return true
        const params = new URLSearchParams()
        params.append('LXHD', username2)
        params.append('MM', password2)
        params.append('SMSCODE', duanxin)
        const { data: res } = await this.$http.post(`${pinT}yonghu/zhaoHuiMiMa`, params)
        if (res.code !== '0000') {
          return this.$message({
            type: 'error',
            message: res.message,
            center: true,
          })
        }
        this.$message({
          type: 'success',
          message: res.message,
          center: true,
        })
        this.isWanjimima = !this.isWanjimima
      })
    },
    // 忘记密码
    wanjimima() {
      this.$refs.loginFormRef.resetFields()
      this.$refs.loginFormRef2.resetFields()
      this.isWanjimima = !this.isWanjimima
      this.loginLoad = false
    },
    // 下载APP
    downloadApp() {
      this.showApp = true
    },
  },
}
</script>
<style lang="scss" scoped>
::v-deep input {
  height: 42px !important;
  line-height: 42px !important;
  font-size: 14px !important;
}
.login_container {
  width: 100%;
  height: 100%;
  background: url('../assets/images/homeBg.png');
  background-repeat: no-repeat;
  background-position: 0 0;
  background-size: 100% 100%;
  position: relative;
  .headBox {
    overflow: hidden;
    padding: 60px 0 0 60px;
    box-sizing: border-box;
    > img {
      height: 55px;
      display: block;
      float: left;
    }
    .logoText {
      float: left;
      height: 55px;
      color: #fff;
      width: 670px;
      margin-left: 10px;
      > span {
        display: inline-block;
        position: absolute;
        height: 100%;
      }
      :first-child {
        font-size: 52px;
        width: 210px;
        top: -10px;
        left: 0;
        position: relative;
        align-items: baseline;
        height: 75px;
        &::before {
          content: '';
          position: absolute;
          right: -20px;
          height: 30px;
          width: 2px;
          background-color: #fff;
          top: 50%;
          transform: translateY(-50%);
        }
      }
      :last-child {
        padding-left: 30px;
        font-size: 21px;
        height: 55px;
        line-height: 55px;
      }
    }
  }
  .main {
    position: absolute;
    left: 60%;
    width: 512px;
    height: 480px;
    top: 50%;
    transform: translateY(-50%);
    .main_bg {
      background-color: #fff;
      opacity: 0.13;
      width: 512px;
      height: 480px;
    }
  }
  .login_main {
    background-color: transparent;
    position: absolute;
    top: 0;
    left: 0;
    width: 512px;
    height: 480px;
    padding: 0 56px;
    box-sizing: border-box;
    top: 50%;
    transform: translateY(-50%);
    .headerBtn {
      // padding-top: 85px;
      // padding-bottom: 73px;
      padding: 60px 0 40px;
      > span {
        cursor: pointer;
        font-size: 20px;
        font-weight: 400;
        padding-right: 20px;
        color: #fff;
        opacity: 0.6;
        &.isShowBtn {
          transform: scale(1.2);
          display: inline-block;
          color: #fff;
          opacity: 1;
          font-weight: 500;
        }
      }
    }
    .btns {
      .el-button {
        width: 100%;
        background-color: #2c66ff;
        border: 0;
        &:hover {
          opacity: 0.6;
          border: 0;
        }
        &:active {
          border: 0;
        }
        &:focus {
          border: 0;
        }
      }
    }
    .btns2 {
      position: relative;
      .text2Box {
        position: absolute;
        left: 0;
        padding: 0;
        color: #fff;
      }
      .el-button {
        position: absolute;
        right: 0;
        padding: 0;
        color: #fff;
      }
    }
    .loginFormRef2 {
      .headerBtn {
        > span {
          color: #fff;
          opacity: 1;
        }
      }
      .btns2 {
        display: flex;
        justify-content: flex-end;
        position: static;
        .el-button {
          position: static;
        }
      }
    }
  }
  .footer {
    &.el-link {
      color: #fff;
      opacity: 0.6;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      bottom: 50px;
      &:hover {
        text-decoration: underline;
      }
    }
  }
}
.qrBox {
  display: flex;
  flex-direction: column;
  // justify-content: center;
  .textsApp {
    text-align: center;
  }
}
::v-deep .footer {
  .el-link--inner {
    font-size: 14px;
  }
}
</style>
